<?php
/**
 * Created by PhpStorm.
 * User: xpz
 * Date: 2021/5/10
 * Time: 17:31
 */

namespace app\admin\controller\company;

use app\common\controller\Backend;
use think\db;

class Chatstyle extends Backend
{
    protected $model = null;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Chatstyle');
    }

    public function index(){
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams('color');
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $result = array("total" => $total, "rows" => $list);


            return json($result);
        }
        return $this->view->fetch();
    }
    
    
    public function add(){
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                //判断前端样式是否存在
                $this->checkCompanyChatStylExist($params['company_id']);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->getCompanyAssign();
        return $this->view->fetch();
    }

    /**
     * 获取公司列表，并赋值给模板
     * @throws \think\exception\DbException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     */
    private function getCompanyAssign(){
        $companyList = collection(model('Company')->where(['status'=>1])->select())->toArray();
        $this->assign('companyList', $companyList);
    }

    /**
     * 判断公司样式是否存在
     * @param $companyId 公司id
     */
    private function checkCompanyChatStylExist($companyId){

        if(!empty($companyId)){
            $companyChatStyleInfo = $this->model->field('id')->where(['company_id'=>$companyId])->find();
            if(!empty($companyChatStyleInfo['id'])){
                $this->error(__('所选公司聊天样式已存在！', ''));
            }
        }
    }

}